package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.entity.content.ActivityApply;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.service.content.ActivityApplyService;
import com.example.everying.service.content.ActivityArticleService;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ApplyStatusMessageHandler implements MessageHandler {

    private static ActivityArticleService activityArticleService;
    private static ActivityApplyService activityApplyService;

    @Autowired
    private void setService(ActivityArticleService activityArticleService,
                            ActivityApplyService activityApplyService) {
        ApplyStatusMessageHandler.activityArticleService = activityArticleService;
        ApplyStatusMessageHandler.activityApplyService = activityApplyService;
    }

    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        String applyId = message.getString("applyId");
        // 根据申请id通知对面的人
        ActivityApply apply = activityApplyService.getById(applyId);
        if (apply == null) {
            log.info("查不到这个申请信息: {}", applyId);
            return;
        }
        ActivityArticle article = activityArticleService.getById(apply.getArtId());
        if (article == null) {
            log.info("查不到这个文章信息: {}", apply.getArtId());
            return;
        }
        JSONObject articleObject = new JSONObject();
        articleObject.put("type", "applyStatusMessage");
        articleObject.put("applyId", applyId);
        log.info("apply:{}",apply);
        log.info("article:{}",article);
        articleObject.put("applyStatus", article.getStatus().equals("3") ? "6" : apply.getOrdersStatus()); // 6 代表发布者完成
        articleObject.put("articleStatus", article.getStatus());
        articleObject.put("refuseNum", apply.getRefuseNum());


        JSONObject applyObject = new JSONObject();
        applyObject.put("type", "applyStatusMessage");
        applyObject.put("applyId", applyId);
        log.info("apply:{}",apply);
        log.info("article:{}",article);
        applyObject.put("applyStatus", apply.getOrdersStatus()); // 6 代表发布者完成
        applyObject.put("articleStatus", article.getStatus());
        applyObject.put("refuseNum", apply.getRefuseNum());


        WebSocketChatService.sendMessageToUserId(apply.getUserId(), applyObject.toJSONString());
        WebSocketChatService.sendMessageToUserId(article.getUserId(), articleObject.toJSONString());


    }
}
